package com.geovis.emergency.spd.controller.system;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.geovis.common.core.api.Result;
import com.geovis.common.core.constant.CommonConstants;
import com.geovis.common.core.controller.BaseController;
import com.geovis.emergency.spd.biz.system.service.ISystemRoleResourcesService;
import com.geovis.emergency.spd.biz.system.service.ISystemRoleService;
import com.geovis.emergency.spd.entity.mobile.pojo.vo.SystemRoleVo;
import com.geovis.emergency.spd.entity.system.entity.SystemMainRole;
import com.geovis.emergency.spd.entity.system.entity.SystemResources;
import com.geovis.emergency.spd.entity.system.entity.SystemRole;
import com.geovis.emergency.spd.entity.system.entity.SystemRoleResources;
import com.geovis.emergency.spd.entity.system.pojo.dto.*;
import com.geovis.emergency.spd.entity.system.pojo.enums.RoleTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author 王响
 * @since 2020-07-15
 */
@RestController
@RequestMapping("/system/systemRole")
@AllArgsConstructor
@Api(value = "系统管理模块-角色相关接口", tags = "系统管理模块-角色相关接口")
@Slf4j
@Validated
public class SystemRoleController extends BaseController<ISystemRoleService> {

    private final ISystemRoleResourcesService systemRoleResourcesService;

    @ApiOperation(value = "保存角色信息", notes = "保存角色信息")
    @PostMapping({"/save"})
    public Result save(@Validated @RequestBody SystemRoleSaveDTO saveDTO) {

        // 1、检查角色名称是否已存在
        Long saveCheckNameCount = baseService.count(Wrappers.lambdaQuery(SystemRole.class).eq(SystemRole::getName, saveDTO.getName()));
        if (saveCheckNameCount > 0) {
            return Result.failed(StrUtil.format("角色名称【{}】已被使用！", saveDTO.getName()));
        }

        if(saveDTO.getRoleType().equals(RoleTypeEnum.SYSTEM))
        {
            if(CollectionUtils.isEmpty(saveDTO.getAuthIds()))
            {
                return Result.failed("权限集合不能为空");
            }
        }

        // 2、检查角色英文名称是否已存在
        Long saveCheckEnNameCount = baseService.count(Wrappers.lambdaQuery(SystemRole.class).eq(SystemRole::getEnName, saveDTO.getEnName()));
        if (saveCheckEnNameCount > 0) {
            return Result.failed(StrUtil.format("角色别名【{}】已被使用！", saveDTO.getEnName()));
        }
        SystemRole systemRole = BeanUtil.toBean(saveDTO, SystemRole.class);

        baseService.save(systemRole);
        //保存权限
        if(saveDTO.getRoleType().equals(RoleTypeEnum.SYSTEM))
        {
            saveSystemRoleResources(systemRole.getId(),saveDTO.getAuthIds());
        }

        return Result.ok();
    }

    private void saveSystemRoleResources(String roleId,List<String> authIds)
    {
        List<SystemRoleResources> srrs=authIds.stream().map(resourceId->{
            SystemRoleResources srr=new SystemRoleResources();
            srr.setRoleId(roleId);
            srr.setResourcesId(resourceId);
            return srr;
        }).collect(Collectors.toList());
        systemRoleResourcesService.saveBatch(srrs);
    }

    @ApiOperation(value = "修改角色信息", notes = "修改角色信息")
    @PostMapping({"/update"})
    public Result update(@Validated @RequestBody SystemRoleUpdateDTO updateDTO) {
        // 1、检查角色名称是否已存在
        Long updateCheckNameCount = baseService.count(Wrappers.lambdaQuery(SystemRole.class)
                .eq(SystemRole::getName, updateDTO.getName())
                .ne(SystemRole::getId, updateDTO.getId()));
        if (updateCheckNameCount > 0) {
            return Result.failed(StrUtil.format("角色名称【{}】已被使用！", updateDTO.getName()));
        }

        // 2、检查角色英文名称是否已存在
        Long updateCheckEnNameCount = baseService.count(Wrappers.lambdaQuery(SystemRole.class)
                .eq(SystemRole::getEnName, updateDTO.getEnName())
                .ne(SystemRole::getId, updateDTO.getId()));
        if (updateCheckEnNameCount > 0) {
            return Result.failed(StrUtil.format("角色英文名称【{}】已被使用！", updateDTO.getEnName()));
        }
        SystemRole systemRole = BeanUtil.toBean(updateDTO, SystemRole.class);
        baseService.updateById(systemRole);
        //保存权限
        if(updateDTO.getRoleType().equals(RoleTypeEnum.SYSTEM))
        {
            systemRoleResourcesService.remove(Wrappers.lambdaUpdate(SystemRoleResources.class).eq(SystemRoleResources::getRoleId, updateDTO.getId()));
            saveSystemRoleResources(updateDTO.getId(),updateDTO.getAuthIds());
        }
        return Result.ok();
    }

    @ApiOperation(value = "查询所有角色数据", notes = "查询所有角色数据")
    @PostMapping("/list")
    public Result<List<SystemRoleVo>> list(@Validated @RequestBody SystemRoleQueryDTO queryDTO) {
        List<SystemRole> roles=baseService.list
                (Wrappers.lambdaQuery(SystemRole.class)
                        .eq(null!=queryDTO.getRoleType(),SystemRole::getRoleType,queryDTO.getRoleType())
                        .like(StrUtil.isNotBlank(queryDTO.getName()),SystemRole::getName,queryDTO.getName())
                        .like(StrUtil.isNotBlank(queryDTO.getEnName()),SystemRole::getEnName,queryDTO.getEnName())
                        .like(StrUtil.isNotBlank(queryDTO.getRemark()),SystemRole::getRemark,queryDTO.getRemark())
                        .orderByAsc(SystemRole::getIdx));


        return Result.ok(roles.stream().map(role->{
            SystemRoleVo roleVo=new SystemRoleVo();
            BeanUtils.copyProperties(role,roleVo);
            List<SystemRoleResources> srrs=systemRoleResourcesService.list(Wrappers.lambdaUpdate(SystemRoleResources.class).eq(SystemRoleResources::getRoleId, role.getId()));
            if(!CollectionUtils.isEmpty(srrs))
            {
                roleVo.setAuthIds(srrs.stream().map(SystemRoleResources::getResourcesId).collect(Collectors.toList()));
            }
            return roleVo;
        }).collect(Collectors.toList()));
    }

    @ApiOperation(value = "批量删除数据", notes = "批量删除数据")
    @ApiImplicitParams({@ApiImplicitParam(name = "idList", value = "删除id的list", required = true, dataType = "java.util.Set", paramType = "body")})
    @PostMapping("/removeByIdList")
    public Result removeByIdList(@NotNull(message = "删除的id集合不能为空") @RequestBody Set<String> idList) {

        if(baseService.checkContainBasicRole(idList))
        {
            return Result.failed("管理员角色和普通用户角色,无法删除");
        }
        String checkResult=baseService.checkRoleUse(idList);
        if(checkResult!=null)
        {
            return Result.failed(checkResult);
        }

        baseService.removeByIdList(idList);
        return Result.ok();
    }


}
